package com.icinfo.cloud.provider.punish.common.datareport.service.impl;

import cn.hutool.json.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.YesOrNoEnum;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.SpringContextUtil;
import com.icinfo.cloud.provider.punish.common.datareport.dto.CaseDataReportRecordQueryDto;
import com.icinfo.cloud.provider.punish.common.datareport.dto.CaseDataReportRequestCommonDto;
import com.icinfo.cloud.provider.punish.common.datareport.enums.CaseDataReportOptTypeEnum;
import com.icinfo.cloud.provider.punish.common.datareport.enums.ReportDataTypeEnum;
import com.icinfo.cloud.provider.punish.common.datareport.service.ICaseDataReportRecordService;
import com.icinfo.cloud.provider.punish.common.datareport.service.ICaseDataReportService;
import com.icinfo.cloud.provider.punish.common.datareport.service.ICaseDataReportStageInfoService;
import com.icinfo.cloud.provider.punish.common.datareport.vo.CaseDataReportRecordVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CasePartiesRecordQueryDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.HandleTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartiesReasonTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseMainInfoService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICasePartiesRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseMainInfoVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CasePartiesInfoVo;
import com.icinfo.framework.common.web.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述：案件数据上报接口实现类-证据信息
 *
 * @author xiangyuyu
 * @date 2022/6/13 20:04
 */
@Slf4j
@Service
public class CaseDataReportObtainServiceImpl implements ICaseDataReportService {

    private static final String TERRITORY_CODE_PREFIX = "001";
    /**
     * 行政处罚证据推送接口
     */
    private static final String OBTAIN_HTTP = "3L7U056ul98eN9f2.htm";
    @Resource
    private ICaseMainInfoService caseMainInfoService;
    @Resource
    private ICaseDataReportStageInfoService caseDataReportStageInfoService;
    @Resource
    private ICaseDataReportRecordService caseDataReportRecordService;
    @Resource
    private ICasePartiesRecordService casePartiesRecordService;

    /**
     * 描述：收集数据上报-证据信息[目前暂不调用-无取证人相关信息]
     *
     * @param caseMainInfoVo {@link CaseMainInfoVo}
     * @param reportDataType 上报数据类型
     * @param isUpdateReReport 是否更新补推CasePartiesInfoVo
     * @param partyInfo {@link CasePartiesInfoVo} 当事人信息
     * @param optType          更新类型
     * @return {@link JSONObject} 上报数据内容
     * @author xiangyuyu
     * @date 2022-03-31 23:18
     */
    @Override
    public JSONObject reportDataCollect(CaseMainInfoVo caseMainInfoVo, String reportDataType, boolean isUpdateReReport,CasePartiesInfoVo partyInfo, String optType) {
        JSONObject returnInfo = new JSONObject();
        log.info("collectReportCaseObtainInfo start...param-caseMainInfo:{},reportDataType:{}", caseMainInfoVo, reportDataType);
        JSONArray obtainInfo = new JSONArray();
        String caseId = caseMainInfoVo.getId();
        String caseTerritoryCode = caseMainInfoVo.getCaseTerritoryCode();
        String sourceDeptCode = TERRITORY_CODE_PREFIX + caseTerritoryCode;
        CaseDataReportRecordQueryDto queryDto = new CaseDataReportRecordQueryDto();
        queryDto.setCaseId(caseId);
        queryDto.setReportDataType(reportDataType);
        queryDto.setIsTestData(YesOrNoEnum.YES.getCode());
        //默认测试数据1
        String envFlag = Constant.STRING_1;
        if (SpringContextUtil.checkIsPrdProfile()) {
            queryDto.setIsTestData(YesOrNoEnum.NO.getCode());
            envFlag = Constant.STRING_0;
        }

        List<CaseDataReportRecordVo> list = caseDataReportRecordService.getCaseDataReportRecord(queryDto);
        String reportActionType = "I";
        if (!ObjectUtils.isEmpty(list) && list.size() > 0) {
            CaseDataReportRecordVo latestRecord = list.get(Constant.INTEGER_0);
            String latestReportResult = latestRecord.getReportResult();
            if (!Constant.STRING_0.equals(latestReportResult)) {
                String oriActionType = latestRecord.getReportActionType();
                reportActionType = "U".equals(oriActionType) ? oriActionType : "I";
            } else {
                reportActionType = "U";
            }
        }

        /*for (T t : ?) {

            JSONObject obtain = new JSONObject();
            obtain.put("recordUniqueIdentity", "");
            obtain.put("punishBaseInfoCode", caseId);
            obtain.put("type", xzcfzj.getType());
            obtain.put("iliegalDescript", StringUtils.isNotEmpty(xzcfzj.getDescription()) ? xzcfzj.getDescription() : "");
            obtain.put("source", StringUtils.isNotEmpty(xzcfzj.getSource()) ? xzcfzj.getSource() : "");
            obtain.put("obtainPersonnel", StringUtils.isNotEmpty(xzcfzj.getObtainPersonnel()) ? xzcfzj.getObtainPersonnel() : "");
            obtain.put("obtainDate", xzcfzj.getObtainDate());
            obtain.put("obtainAddress", StringUtils.isNotEmpty(xzcfzj.getObtainAddress()) ? xzcfzj.getObtainAddress() : "");
            obtain.put("optType", xzcfzj.getOptType());
            obtain.put("envFlag", jgCase.getEnvFlag());
            obtain.put("sourceDeptCode", sourceDeptCode + jgCase.getBaseInfo().getDomain());
            obtainInfo.add(obtain);
        }*/
        returnInfo.put("obtainInfo", obtainInfo);
        //到dataReport时清空该键值
        returnInfo.put("reportActionType", !ObjectUtils.isEmpty(optType)?optType:reportActionType);
        returnInfo.put("envFlag", envFlag);
        log.info("collectReportCaseObtainInfo end...result-returnInfo", returnInfo);
        return returnInfo;
    }



    /**
     * 描述：数据上报-obtain [目前暂不调用-无取证人相关信息]
     *
     * @param dto          {@link CaseDataReportRequestCommonDto}
     * @param partyInfo    {@link CasePartiesInfoVo} 当事人信息
     * @param caseMainInfo {@link CaseMainInfoVo} 案件主体信息
     * @return {@link Result<String>} 上报结果
     * @author xiangyuyu
     * @date 2022-03-30 21:23
     */
    @Override
    public Result<String> singleCaseReport(CaseDataReportRequestCommonDto dto, CasePartiesInfoVo partyInfo, CaseMainInfoVo caseMainInfo) {
        log.info("dataReportObtain start... dto:{}", dto);
        String caseId = dto.getCaseId();
        String optType = dto.getOptType();
        if(!ObjectUtils.isEmpty(optType)){
            if(!CaseDataReportOptTypeEnum.isLegalEnumCode(optType)){
                throw new BusinessException("请指定有效的数据上报更新类型枚举(I：新增， U：修改； D：删除)");
            }
        }
        if (!caseDataReportRecordService.personalCheckIsAllowDataReport(caseId, null)) {
            log.info("该案件暂不开启数据上报-caseId:{}", caseId);
            return Result.error("该案件暂不开启数据上报-caseId:" + caseId);
        }
        List<CasePartiesInfoVo> partiesInfo = new ArrayList<>();
        if (ObjectUtils.isEmpty(partyInfo)) {
            //获取当事人信息
            if (ObjectUtils.isEmpty(caseMainInfo)) {
                caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
            }
            String casePartiesReasonType = caseMainInfo.getCasePartiesReasonType();
            String handleType = caseMainInfo.getHandleType();
            CasePartiesRecordQueryDto queryDto = new CasePartiesRecordQueryDto(caseId, null, YesOrNoEnum.NO.getCode());
            partiesInfo = casePartiesRecordService.getCasePartiesInfoList(queryDto);
            if (!(PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(casePartiesReasonType)
                    && HandleTypeEnum.PART_PUNISH.getCode().equals(handleType))
            ) {
                //只取第一个当事人信息
                List<CasePartiesInfoVo> tmp = new ArrayList<>();
                tmp.add(partiesInfo.get(Constant.INTEGER_0));
                partiesInfo = tmp;
                partiesInfo.forEach(p -> p.setPartyId(null));
            }
        } else {
            partiesInfo.add(partyInfo);
        }

        for (CasePartiesInfoVo p : partiesInfo) {
            String partyId = p.getPartyId();
            try {
                if (caseDataReportRecordService.getIsAllowDataReport(caseId)) {
                    String errorMsg;
                    if (ObjectUtils.isEmpty(caseMainInfo)) {
                        //根据案件id查询案件信息
                        caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
                    }
                    String caseType = caseMainInfo.getCaseType();
                    if (CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseType)) {
                        //简易处罚直接跳过
                        return Result.success("简易处罚直接跳过证据信息数据上报");
                    }
                    String uri = OBTAIN_HTTP;
                    String reportDataType = ReportDataTypeEnum.OBTAIN.getCode();
                    JSONObject reportData = reportDataCollect(caseMainInfo, reportDataType, false, p, optType);
                    reportData.put("reportActionType", !ObjectUtils.isEmpty(optType)?optType:reportData.get("reportActionType"));
                    Map<String, String> params = new HashMap<>(20);
                    for (Map.Entry<String, Object> e : reportData.entrySet()) {
                        params.put(e.getKey(), (ObjectUtils.isEmpty(e.getValue()) ? "" : e.getValue().toString()));
                    }
                    errorMsg = caseDataReportRecordService.dataReport(uri, reportDataType, params, caseMainInfo);
                    log.info("dataReportObtain end");
                    if (ObjectUtils.isEmpty(errorMsg)) {
                        caseDataReportStageInfoService.dealAfterReport(caseId, true, ReportDataTypeEnum.OBTAIN.getCode(), null, partyId);
                        return Result.success("上报成功");
                    } else {
                        if (errorMsg.contains(Constant.STRING_RECORD_EXISTS)) {
                            caseDataReportStageInfoService.dealAfterReport(caseId, true, ReportDataTypeEnum.OBTAIN.getCode(), errorMsg, partyId);
                        } else if(errorMsg.contains(Constant.STRING_ERROR_SIGN)) {
                            caseDataReportRecordService.reportAgain(dto, partyInfo, caseMainInfo, this, reportDataType);
                        } else {
                            caseDataReportStageInfoService.dealAfterReport(caseId, false, ReportDataTypeEnum.OBTAIN.getCode(), errorMsg, partyId);
                        }
                        return Result.error(errorMsg);
                    }
                } else {
                    String tmpMsg = "该部门是否允许上报数据按钮处于关闭状态,caseId:" + caseId;
                    throw new BusinessException(tmpMsg);
                }
            } catch (Exception e) {
                e.printStackTrace();
                caseDataReportStageInfoService.dealAfterReport(caseId, false, ReportDataTypeEnum.OBTAIN.getCode(), e.getMessage(), partyId);
                return Result.error("dataReportObtain catch exception：" + e.getMessage());
            }
        }
        return Result.success(Constant.STRING_OPERATE_SUCCESS);
    }

    /**
     * 描述：批量案件数据上报
     * @param baseInfoReportFailCaseIdList 上报失败的案件id列表
     * @return {@link Result <String>} 上报失败案件id列表
     * @author xiangyuyu
     * @date 2022-06-13 18:52
     */
    @Override
    public List<String> batchCaseReport(List<String> baseInfoReportFailCaseIdList) {
        if(ObjectUtils.isEmpty(baseInfoReportFailCaseIdList)){
            baseInfoReportFailCaseIdList = new ArrayList<>();
        }
        return null;
    }

    /**
     * 描述：单个案件重新数据上报（U）
     *
     * @param caseId 案件id
     * @param partyInfo    {@link CasePartiesInfoVo} 当事人信息
     * @param caseMainInfo {@link CaseMainInfoVo} 案件主体信息
     * @return {@link Result <String>} 上报结果
     * @author xiangyuyu
     * @date 2022-06-13 18:52
     */
    @Override
    public Result<String> singleCaseReportAgain(String caseId, CasePartiesInfoVo partyInfo, CaseMainInfoVo caseMainInfo) {
        return null;
    }

    /**
     * 描述：批量案件重新数据上报（U）
     *
     * @return {@link Result <String>} 上报失败案件id列表
     * @author xiangyuyu
     * @date 2022-06-13 18:52
     */
    @Override
    public List<String> batchCaseReportAgain() {
        return null;
    }


}
